package com.github.ghsea.sso.client.security.cas;

import com.github.ghsea.sso.client.security.shiro.RedisSessionDAO;
import com.github.ghsea.sso.client.config.ShiroConfig;
import java.util.Arrays;
import java.util.Optional;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author guhai
 */
@Component
public class UserInfoUtils {

    @Autowired
    private RedisSessionDAO sessionDAO;

    @Autowired
    private ShiroConfig shiroConfig;

    public static UserPrincipal getPrincipal() {
        Subject subject = SecurityUtils.getSubject();
        return (UserPrincipal) subject.getPrincipal();
    }

    public static Session getSession() {
        try {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession(false);
            if (session == null) {
                session = subject.getSession();
            }
            if (session != null) {
                return session;
            }
        } catch (InvalidSessionException e) {

        }
        return null;
    }

    /**
     * 查询request所对应的Session
     *
     * @param request
     * @return
     */
    public Optional<Session> getSession(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            Optional<Cookie> ssoCookie = Arrays.stream(cookies).filter(e -> shiroConfig.getSessionKey().equals(e.getName())).findFirst();
            if (ssoCookie.isPresent()) {
                return Optional.ofNullable(sessionDAO.readSession(ssoCookie.get().getValue()));
            }
        }

        String token = WebUtil.getAuthTokenFromHeader(request);
        if (token != null) {
            return Optional.ofNullable(sessionDAO.readSession(token));
        }

        return Optional.empty();

    }

}
